package com.test.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.test.pojo.TbCart;
import com.test.pojo.TbSku;
import com.test.service.TbCartService;
import com.test.service.TbSkuService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yanglijun
 * @since 2020-12-16
 */
@RestController
@RequestMapping("/tb-cart")
public class TbCartController {

    @Resource
    private TbCartService tbCartService;

    @Resource
    private TbSkuService tbSkuService;

    /*分页获取商品*/
    @GetMapping("/getCartPage")
    public IPage<TbCart> getPage(Integer current, String username){
        QueryWrapper<TbCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Page<TbCart> page = new Page<>(current,8);
        return tbCartService.page(page,queryWrapper);
    }
    /*商品删除*/
    @GetMapping("/deleteGood")
    public boolean deleteGood(String id){
        boolean removeById = tbCartService.removeById(id);
        if (removeById){
            return true;
        }
        return false;
    }
    /*获取前端购物车选中数据*/
    @PostMapping("/setCartlist")
    public boolean setCartlist(@RequestBody JSONArray shopcarlist){
        System.out.println(shopcarlist);
        String s = shopcarlist.toJSONString();
        List<TbCart> tbCarts = JSONArray.parseArray(s, TbCart.class);
        for (TbCart c:tbCarts){
           tbCartService.saveOrUpdate(c);
        }
        return true;
    }
    /* 查库存*/
    @GetMapping("/shopkucun")
    public Integer shopkucun(String id) {
        TbSku tbSku = tbSkuService.getById(id);
        Integer num = tbSku.getNum();
        return num;
    }
    /* 修改库存字段 UPDATE `tb_cart` SET `total_num`=?,`subtotal_money`=? WHERE `id`=?*/
    @GetMapping("/updatekucun")
    public boolean updatekucun(Integer totalNum,Integer subtotalMoney,String id) {
        System.out.println("**********************"+totalNum+subtotalMoney+id);
        TbCart tbCart=new TbCart();
        tbCart.setTotalNum(totalNum);
        tbCart.setId(id);
        tbCart.setSubtotalMoney(subtotalMoney);
        boolean update = tbCartService.update(tbCart, new UpdateWrapper<TbCart>().eq("id", id));
        if (update){
            return true;
        }
        return false;
    }


}

